import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiBody,
} from '@nestjs/swagger';
import { CartService } from './cart.service';
import type { CartItem } from './cart.service';

@ApiTags('购物车')
@Controller('cart')
export class CartController {
  constructor(private readonly cartService: CartService) {}

  @ApiOperation({ summary: '获取用户购物车' })
  @ApiResponse({ status: 200, description: '成功获取购物车' })
  @ApiBearerAuth()
  @Get(':userId')
  findUserCart(@Param('userId') userId: string): CartItem[] {
    return this.cartService.findUserCart(userId);
  }

  @ApiOperation({ summary: '添加商品到购物车' })
  @ApiResponse({ status: 201, description: '商品添加成功' })
  @ApiBearerAuth()
  @ApiBody({ 
    schema: { 
      type: 'object', 
      properties: { 
        userId: { type: 'string' },
        productId: { type: 'string' },
        productType: { type: 'string', enum: ['ticket', 'group-buy'] },
        quantity: { type: 'number' }
      } 
    } 
  })
  @Post()
  @HttpCode(HttpStatus.CREATED)
  addToCart(
    @Body('userId') userId: string,
    @Body('productId') productId: string,
    @Body('productType') productType: 'ticket' | 'group-buy',
    @Body('quantity') quantity: number = 1,
  ): CartItem {
    return this.cartService.addToCart(userId, productId, productType, quantity);
  }

  @ApiOperation({ summary: '更新购物车商品数量' })
  @ApiResponse({ status: 200, description: '购物车更新成功' })
  @ApiResponse({ status: 404, description: '购物车项不存在' })
  @ApiBearerAuth()
  @ApiBody({ schema: { type: 'object', properties: { quantity: { type: 'number' } } } })
  @Put(':id')
  updateCartItem(
    @Param('id') id: string,
    @Body('quantity') quantity: number,
  ): CartItem | null {
    const result = this.cartService.updateCartItem(id, quantity);
    if (!result && quantity > 0) {
      throw new Error('Cart item not found');
    }
    return result;
  }

  @ApiOperation({ summary: '从购物车删除商品' })
  @ApiResponse({ status: 204, description: '商品删除成功' })
  @ApiResponse({ status: 404, description: '购物车项不存在' })
  @ApiBearerAuth()
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  removeFromCart(@Param('id') id: string): void {
    const result = this.cartService.removeFromCart(id);
    if (!result) {
      throw new Error('Cart item not found');
    }
  }

  @ApiOperation({ summary: '清空用户购物车' })
  @ApiResponse({ status: 204, description: '购物车清空成功' })
  @ApiBearerAuth()
  @Delete('clear/:userId')
  @HttpCode(HttpStatus.NO_CONTENT)
  clearUserCart(@Param('userId') userId: string): void {
    this.cartService.clearUserCart(userId);
  }
}